/*
 * Copyright (C) 2011, 2012 Moravská zemská knihovna v Brně / Moravian Library in Brno
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cz.mzk.oai.provider;

import cz.mzk.oai.provider.response.OaiErrorResponse;
import cz.mzk.oai.provider.response.OaiVerbResponse;
import cz.mzk.oai.provider.response.listRequests.ResumptionTokenManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class Servlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger(Servlet.class.getName());

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String requestUrl = request.getRequestURL().toString();
            OaiRequestParameters parameters = new OaiRequestParameters(request);
            logger.log(Level.INFO, "{0} ({1})", new Object[]{requestUrl, parameters.toString()});
            String baseUrl = request.getRequestURL().toString();
            Map<String, String[]> parameterMap = parameters.getMap();
            Document responseDoc;
            String verbStr = null;
            try {
                verbStr = getVerbStr(parameterMap);
                parameterMap.remove("verb");
                OaiVerbResponse verbResponse = VerbFactory.getVerbResponse(verbStr, parameterMap, baseUrl);
                responseDoc = verbResponse.build();
            } catch (OaiException ex) {
                OaiErrorResponse errorResponse = new OaiErrorResponse(verbStr, parameterMap, ex.getCode(), ex.getMessage(), baseUrl);
                responseDoc = errorResponse.build();
                logger.log(Level.WARNING, "{0}: {1}", new Object[]{ex.getCode().toString(), ex.getMessage()});
            }
            printDoc(out, responseDoc);
            ResumptionTokenManager.clearOldResumptionTokens();
        } finally {
            out.close();
        }
    }

    private static String getVerbStr(Map<String, String[]> parameters) throws OaiException {
        String[] values = parameters.get("verb");
        if (values == null) {
            throw new OaiException(ErrorCode.badVerb, "Missing verb");
        }
        if (values.length != 1) {
            throw new OaiException(ErrorCode.badVerb, "Multiple verbs(" + values.length + ")");
        }
        return values[0];
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void printDoc(PrintWriter out, Document responseDoc) {
        //TODO: optimalizovat
        String string = responseDoc.asXML().toString();
        out.print(string);
    }

    private Map<String, String[]> getParameterMap(HttpServletRequest request) throws UnsupportedEncodingException {
        Enumeration<String> parameterNames = request.getParameterNames();
        HashMap<String, String[]> result = new HashMap<String, String[]>();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String[] values = request.getParameterValues(name);
            String[] decodedValues = new String[values.length];

            StringBuilder valuesString = new StringBuilder();
            StringBuilder decodedValuesString = new StringBuilder();
            valuesString.append("[");
            decodedValuesString.append("[");
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                String urlDecoded = URLDecoder.decode(value, "UTF-8");
                decodedValues[i] = urlDecoded;

                valuesString.append(value);
                decodedValuesString.append(urlDecoded);
                if (i != values.length - 1) {
                    valuesString.append(", ");
                    decodedValuesString.append(", ");
                }
            }
            result.put(name, decodedValues);
            valuesString.append("]");
            decodedValuesString.append("]");
            logger.log(Level.FINE, "{0}: recieved={1}, decoded={2}", new Object[]{name, valuesString, decodedValuesString});
        }
        return result;
    }
}
